using System;
using System.Threading;
using Emgu.CV;
using Emgu.CV.Structure;
using NIPO.Data;
using NIPO.Plugins;


namespace NIPOCvPlugins.CameraInputPlugin
{
    public class CameraInputPlugin : InputPlugin
    {
        private Emgu.CV.Capture _capture;
        #region Overrides of Plugin

        protected override void Initialize()
        {
            _capture = new Emgu.CV.Capture();
            _capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, 640);
            _capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, 480);
            Log.WriteInfoFormat("Capture will produce {0}x{1} images",
                                _capture.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH),
                                _capture.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT));
        }

        public override void Dispose()
        {
            _capture.Dispose();
        }

        public override bool IsConfigured
        {
            get { return true; }
        }

        #endregion

        #region Overrides of IPOPlugin

        public override void Reset()
        {

        }

        #endregion

        #region Overrides of InputPlugin

        public override void Run()
        {
            while (!Abort)
            {
                
                Image<Bgr, byte> image = _capture.QuerySmallFrame();
                if (image != null && image.Data != null)
                    RaiseNewData(new GenericDTO<Image<Bgr, byte>>(image, "EMGU/Image<Bgr, byte>", image.Bytes.Length,
                                                                       DateTime.Now));
                Thread.Sleep(40);
            }
        }

        #endregion
    }
}